#include "CocosPCH.h"

#include "SpineAnimateCache.h"
#include "spine/SkeletonJson.h"
#include "renderer/CCTexture2D.h"

using namespace std;

static std::string s_spine_path = "";

spSkeletonData* SpineAnimateCache::addCache(const std::string& filename, float scale)
{
	string jsonFileName = s_spine_path + filename + string(".json");
	string atlasFileName = s_spine_path + filename + string(".atlas");
	string imgFileName = s_spine_path + filename + string(".png");

	cocos2d::Texture2D* textture =cocos2d::Director::getInstance()->getTextureCache()->addImage(imgFileName);
	if (textture)
		_textureCache.insert(imgFileName);

	spSkeletonData* spDatap = NULL;
	if (_skeletonDataCacheMap.find(filename) == _skeletonDataCacheMap.end())
	{
		spAtlas* _atlas = spAtlas_createFromFile(atlasFileName.c_str(), 0);
		CCASSERT(_atlas, "Error reading atlas file.");

		spSkeletonJson* json = spSkeletonJson_create(_atlas);
		json->scale = scale;
		spSkeletonData* skeletonData = spSkeletonJson_readSkeletonDataFile(json, jsonFileName.c_str());
		spDatap = skeletonData;
		
		if (spDatap)
			_skeletonDataCacheMap.insert(SKELETON_DATA_CACHE_MAP::value_type(filename, SpSkeletonDataPtr(skeletonData)));
	}
		
	return spDatap;
}

void SpineAnimateCache::cleanCache()
{
	_skeletonDataCacheMap.clear();
	for (auto it = _textureCache.begin(); it != _textureCache.end();it++)
	{
		cocos2d::Director::getInstance()->getTextureCache()->removeTextureForKey(*it);
	}
}

spine::SkeletonAnimation* SpineAnimateCache::getSpAnimate(const string& filename,float scale)
{
	SKELETON_DATA_CACHE_MAP::iterator it = _skeletonDataCacheMap.find(filename);
	spSkeletonData* spDatap = NULL;
	if (it != _skeletonDataCacheMap.end())
	{
		SpSkeletonDataPtr spSkeletonPtr = it->second;
		spDatap = spSkeletonPtr.get();
	}
	else
	{
		spDatap = addCache(filename, scale);

	}
	if (!spDatap)
	{
		return NULL;
	}

	spine::SkeletonAnimation* spineAnimate = spine::SkeletonAnimation::createWithData(spDatap);
	return spineAnimate;
}

